<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 资讯信息
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form ref="formModel" :rules="ruleValidate" :model="bloc.form" :label-width="100" label-position="right">
        <FormItem label="资讯分类:">
          <i-select v-model="bloc.sortInfo.name" style="width:415px; margin-right: 10px" filterable>
            <i-option :value="bloc.sortInfo.name" disabled>{{ bloc.sortInfo.name }}</i-option>
          </i-select>
        </FormItem>
        <FormItem label="资讯标题:" prop="title" required>
          <Input type="text" v-model="bloc.form.title" placeholder="请填写资讯标题" style="width: 400px"/>
        </FormItem>
        <FormItem label="是否显示:">
          <i-switch v-model="bloc.form.enable"></i-switch>
        </FormItem>
        <FormItem label="图片列表:">
          <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
            <template v-if="item.status === 'finished'">
              <img :src="item.url">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            v-show="fileList.length < 1"
            ref="upload"
            :show-upload-list="false"
            :format="['jpg','jpeg','png']"
            :max-size="500"
            :headers="uploadHeaders"
            :action="uploadAction"
            :on-success="handleSuccess"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            multiple
            type="drag"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <span style="margin-left: 20px;color: #c2c7d0">（支持jpg,png,图片最大为500k,最多上传一张）</span>
          <Modal title="View Image" v-model="visible">
            <img :src="imgUrl" v-if="visible" style="width: 100%">
          </Modal>
        </FormItem>
        <FormItem label="资讯正文:" prop="body" required>
          <HtmlEditor
            id="ueditor"
            :config="config"
            :content="bloc.initContent"
            :useCustomUpload="true"
            @change="ueditorChange"
            style="width: 100%; max-width: 1000px; overflow: auto"
          ></HtmlEditor>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <Button type="primary" style="margin-left: 30px;width: 100px;height: 40px;" :loading="btnload.loading"
                @click="handleOk()">保存
        </Button>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';
  import {Route} from 'vue-router';
  import {FormBloc} from '@/view/info/bloc/FormBloc';
  import {baseUrl} from '@/base/Request';
  import {store} from '@/store/Store';
  import HtmlEditor from '@/component/HtmlEditor.vue';
  import {Loading} from '@/base/Loading';
  import {isEmpty} from '@/base/util/Strings';
  import {getValidateMaxString} from '@/base/util/Validate';

  @Component({
    components: {HtmlEditor}
  })
  export default class extends Vue {
    beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
      next(vm => {
        vm.bloc.sortId = Number(vm.$route.query.sortId);
        vm.bloc.loadSort();
        if (!vm.isAdd) vm.bloc.load(vm.idx);
      });
    }

    get fileList() {
      return this.bloc.form.images.map(x => {
        return {'name': 'name', 'url': x, 'status': 'finished'};
      });
    }

    get isAdd() {
      return !this.idx;
    }

    get idx() {
      return Number(this.$route.params.id);
    }

    get uploadAction() {
      return `${baseUrl}/api/upload/image`;
    }

    get uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + store.state.auth.accessToken
      };
    };

    bloc: FormBloc = new FormBloc();
    btnload = new Loading();
    imgUrl = '';
    visible = false;

    config = {
      imageUrl: this.uploadAction, // 图片上传提交地址
      imagePath: '',
      imageToken: store.state.auth.accessToken,
      imageFieldName: 'file'
    };

    ruleValidate = {
      title: [
        {
          validator: (rule, value, callback) => {
            if (isEmpty(value)) {
              callback(new Error('资讯标题不能为空'))
            } else if (getValidateMaxString(15, value)) {
              callback(new Error('资讯标题的长度不能超过15'))
            } else callback()
          },
          trigger: 'blur'
        }
      ],
      body: [
        {required: true, message: '请填写资讯正文', trigger: 'blur'}
      ]
    };

    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    }

    handleRemove(file) {
      this.bloc.form.images.splice(this.bloc.form.images.indexOf(file), 1);
    }

    handleSuccess(res, file) {
      this.bloc.form.images.push(res.data[0]);
    }

    handleFormatError(file) {
      this.$Message.warning(`${file.name}格式不正确，请上传jpg或png格式的图片`);
    }

    handleMaxSize(file) {
      this.$Message.error('请上传不大于500k的图片');
    }

    ueditorChange(ue) {
      this.bloc.form.body = ue.getContent();
    }

    handleCancel() {
      this.$router.push({path: '/info', query: {sortId: this.bloc.sortId + ''}});
    }

    handleOk() {
      const formRef: any = this.$refs['formModel'];
      formRef.validate((valid) => {
        if (valid) {
          this.saveFn();
        }
      });
    }

    saveFn() {
      this.btnload.loading = true;
      const parmas = this.isAdd ? '' : this.idx;
      this.bloc.save(parmas).then(res => {
        this.$Message.success('保存成功');
        this.btnload.loading = false;
        this.bloc.resetForm();
        this.handleCancel();
      }).catch(err => {
        this.btnload.loading = false;
        this.$Message.error('保存失败');
        console.log('出错啦::::', err);
      });
    }
  }
</script>

<style lang="less" scoped>
</style>
